package com.alisls.activiti.service.service.impl;

import com.alisls.activiti.service.entity.SysUser;
import com.alisls.activiti.service.service.SysUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * SpringSecurity接口UserDetailService默认实现类
 *
 * @author Ke Wang
 */
@Service("customUserDetailService")
public class CustomUserDetailServiceImpl implements UserDetailsService {

    @Resource
    private SysUserService sysUserService;

    /**
     * 根据用户名加载用户
     * @param username 用户名
     * @return 用户
     * @throws UsernameNotFoundException 用户不存在异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户不存在！");
        }

        // TODO 设置用户权限
        Set<GrantedAuthority> authorities = new HashSet<>();
        /*
         * 给用户添加角色ROLE_ACTIVITI_USER（有该角色才可以使用ProcessRuntime/TaskRuntime）
         * 候选组GROUP_MANAGER_TEAM
         */
        authorities.add(new SimpleGrantedAuthority("ROLE_ACTIVITI_USER"));
        authorities.add(new SimpleGrantedAuthority("GROUP_MANAGER_TEAM"));
        sysUser.setAuthorities(authorities);

        return sysUser;
    }

}
